package com.mti.ftp.util;

import com.mti.ftp.factory.FtpClientFactory;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Service
@Log4j2
public class FtpUtils {

    @Value("${ftp.baseDir}")
    private String remotePath;

    @Autowired
    private FtpClientFactory ftpClientFactory;

    public boolean uploadFile(File file) throws IOException {
        FTPClient ftpClient = ftpClientFactory.createFtpClient();
        try {

            // 创建远程目录（如果不存在）
            if (!remotePath.isEmpty()) {
                createRemoteDirectory(ftpClient, remotePath);
            }

            // 上传文件
            try (FileInputStream inputStream = new FileInputStream(file)) {
                String remoteFilePath = remotePath + "/" + file.getName();
                return ftpClient.storeFile(remoteFilePath, inputStream);
            }
        } finally {
            ftpClientFactory.disconnect(ftpClient);
        }
    }

    private void createRemoteDirectory(FTPClient ftpClient, String remotePath) throws IOException {
        String[] directories = remotePath.split("/");
        for (String dir : directories) {
            if (!dir.isEmpty() && !ftpClient.changeWorkingDirectory(dir)) {
                if (!ftpClient.makeDirectory(dir)) {
                    throw new IOException("无法创建远程目录: " + dir);
                }
                ftpClient.changeWorkingDirectory(dir);
            }
        }
    }

    public InputStream downloadFile(String remoteFilePath) throws IOException {
        FTPClient ftpClient = ftpClientFactory.createFtpClient();
        try {
            // 获取文件输入流
            String convertedString = new String(remoteFilePath.getBytes(), StandardCharsets.ISO_8859_1);
            InputStream inputStream = ftpClient.retrieveFileStream(convertedString);
            if (inputStream == null) {
                throw new IOException("无法获取文件流: " + remoteFilePath);
            }

            // 确保命令完成
            boolean success = ftpClient.completePendingCommand();
            if (!success) {
                throw new IOException("文件下载失败: " + remoteFilePath);
            }
            return inputStream;
        } finally {
            ftpClientFactory.disconnect(ftpClient);
        }
    }


}
